package com.szxy.lockdemo;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @Author: zwz
 * @Date:2020/10/23 18:52
 * @Description: 手动实现自旋锁
 **/
public class SpinLock {
    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void lock() {
        Thread thread = Thread.currentThread();
        System.out.println(thread + " coming...");
        while (!atomicReference.compareAndSet(null, thread)) {
            // loop
        }
    }

    public void unlock() {
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread, null);
        System.out.println(thread + " unlock...");
    }

    public static void main(String[] args) throws InterruptedException {
        SpinLock spinLock = new SpinLock();

        new Thread(() -> {
            spinLock.lock();
            try {
                Thread.sleep(3000);
                System.out.println("hahaha");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                spinLock.unlock();
            }
        }).start();

        Thread.sleep(1000);

        new Thread(() -> {
            spinLock.lock();
            System.out.println("hehehe");
            spinLock.unlock();
        }).start();
    }
}
